package com.stoneframe.plugin.websocketInstantMsg;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.java_websocket.WebSocket;

/**
 * 即时通讯
 */
public class ChatServerPool {
	
	private static final Map<WebSocket,String> userConn=new HashMap<WebSocket,String>();

	/**
	 * 获取用户名
	 */
	public static String getUserByKey(WebSocket conn){
		return userConn.get(conn);
	}
	
	/**
	 * 获取WebSocket
	 */
	public static WebSocket getWebSocketByUser(String user){
		Set<WebSocket> keySet=userConn.keySet();
		synchronized(keySet){
			for(WebSocket conn:keySet){
				if(user.equals(userConn.get(conn))){
					return conn;
				}
			}
		}
		return null;
	}
	
	/**
	 * 向连接池中添加连接
	 */
	public static void addUser(WebSocket conn,String user){
		userConn.put(conn, user);
	}
	
	/**
	 * 获取所有的用户
	 */
	public static Collection<String> getUser(){
		List<String> userList=new ArrayList();
		Collection<String> setUser=userConn.values();
		for(String u:setUser){
			userList.add(u);
		}
		return userList;
	}
	
	/**
	 * 移除连接池中的连接
	 */
	public static boolean removeUser(WebSocket conn){
		if(userConn.containsKey(conn)){
			userConn.remove(conn);
			return true;
		}
		return false;
	}
	
	/**
	 * 向特定的用户发送数据
	 */
	public static void sendMessage(WebSocket conn,String message){
		if(null!=conn&& null!=userConn.get(conn)){
			conn.send(message);
		}
	}
	
	/**
	 * 向所有的用户发送消息
	 */
	public static void sendMessage(String message){
		Set<WebSocket> keySet=userConn.keySet();
		synchronized(keySet){
			for(WebSocket conn:keySet){
				if(null!=userConn.get(conn)){
					conn.send(message);
				}
			}
		}
	}
	
}
